package com.hk.kindheartedness;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.hk.kindheartedness.db.DBOpenHelper;
import com.hk.kindheartedness.util.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 医生病历业务处理
 */
public class DoctorCaseHistoryActivity extends AppCompatActivity {

    //    Initialize Toast
    private Toast toast;

    //    Initialize intent
    private Intent intent;

    //    声明DBOpenHelper对象
    private DBOpenHelper dbOpenHelper;

    private String loginDoctorId;

    private ListView querySetADoctorListView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_doctor_case_history);
//        实例化
        dbOpenHelper = new DBOpenHelper(DoctorCaseHistoryActivity.this, "db_kindheartedness", null, 1);
//        获取ListView控制权
        querySetADoctorListView = findViewById(R.id.querySetADoctorListView);
//        获取当前登录医生Id
        Intent intent2 = getIntent();
        final Bundle bundle = intent2.getExtras();
        loginDoctorId = bundle.getString("loginDoctorId");
        Log.i("当前登录医生ID：", loginDoctorId);
//        查询并回显该医生相关的预约患者
        findByDoctorId(loginDoctorId);

        //        添加长按点击弹出选项框菜单
        querySetADoctorListView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                menu.setHeaderTitle("选择操作！");
                menu.add(0, 0, 0, "开具病历");
                menu.add(0, 1, 0, "更新病历");
            }
        });

    }

    /**
     * 给菜单项添加事件
     *
     * @param item 菜单索引
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {
//        获取上下文
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
//        得到listView中选择的条目绑定的Id
        String id = String.valueOf(info.id);
//        得到列表子节点的视图
        View targetView = info.targetView;
        //                获取单列 某一元素的控制权
        TextView registrationLogId = targetView.findViewById(R.id.registrationLogId);
//                获取元素内容 手机号
        String registrationLogIdToString = registrationLogId.getText().toString();
        Log.i("=====ListView列表绑定的ID==", id);
        Log.i("===== 对应的患者挂号记录Id==", registrationLogIdToString);
        switch (item.getItemId()) {
            case 0:
//                开具病历事件的方法
                addDiaLog(registrationLogIdToString);
                return true;
            case 1:
//                更新病历事件的方法
                updateData(registrationLogIdToString);
                return true;
            default:
                return super.onContextItemSelected(item);
        }
    }

    /**
     * 更新病历
     * @param registrationLogIdToString 患者挂号记录Id
     */
    private void updateData(String registrationLogIdToString) {
        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
//            查询当前患者挂号记录病历是否已开具
        Cursor queryCaseHistory = readableDatabase.query("case_history", null, "registration_log_id = ?", new String[]{registrationLogIdToString}, null, null, null);
        String caseHistoryId = null;
        while (queryCaseHistory.moveToNext()) {
            caseHistoryId = queryCaseHistory.getString(0);
        }
        if (caseHistoryId == null) {
            toast = ToastUtil.toastHint(toast,DoctorCaseHistoryActivity.this,"病历暂未开具!");
            return;
        }
        intent = new Intent(DoctorCaseHistoryActivity.this,DoctorUpdateCaseHistoryActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("registrationLogId",registrationLogIdToString);
        bundle.putString("loginDoctorId",loginDoctorId);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    /**
     * 将挂号记录传递到开具病历页面
     * @param registrationLogIdToString 患者挂号记录Id
     */
    private void addDiaLog(String registrationLogIdToString) {
        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
//            查询当前患者挂号记录病历是否已开具
        Cursor queryCaseHistory = readableDatabase.query("case_history", null, "registration_log_id = ?", new String[]{registrationLogIdToString}, null, null, null);
        String caseHistoryId = null;
        while (queryCaseHistory.moveToNext()) {
            caseHistoryId = queryCaseHistory.getString(0);
        }
        if (caseHistoryId != null) {
            toast = ToastUtil.toastHint(toast,DoctorCaseHistoryActivity.this,"病历已开具,请勿重新开具!");
            return;
        }
        intent = new Intent(DoctorCaseHistoryActivity.this,DoctorAddCaseHistoryActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("registrationLogId",registrationLogIdToString);
        bundle.putString("loginDoctorId",loginDoctorId);
        intent.putExtras(bundle);
        startActivity(intent);
    }


    /**
     * 查询医生相关预约患者信息并回显
     *
     * @param loginDoctorId 医生Id
     */
    private void findByDoctorId(String loginDoctorId) {
        /**
         * 1、通过医生Id查询所有设置的挂号记录，提取出挂号记录Id集合、就诊日期、时间
         * 2、通过挂号记录Id查询相关的患者挂号信息，提取出患者Id、预约时间、状态
         * 3、通过患者Id查询患者信息，提取出患者姓名
         * 4、进行封装保存回显
         */
        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
        Cursor queryRegistrationSetting = readableDatabase.query("registration_setting", null, "doctor_id = ?", new String[]{loginDoctorId}, null, null, "registration_date desc");
//        存储获取到的数据
        List<Map<String, Object>> resultList = new ArrayList<>(10);
        while (queryRegistrationSetting.moveToNext()) {
            Map<String, Object> map = new HashMap<>(8);
            String registrationId = queryRegistrationSetting.getString(0);
            String registrationDate = queryRegistrationSetting.getString(2);
            String registrationTime = queryRegistrationSetting.getString(3);
            map.put("setADoctorTime", registrationDate + "\n" + registrationTime);
//            通过Id查询对应患者挂号记录,可能有多个患者预约
            Cursor queryRegistrationLog = readableDatabase.query("registration_log", null, "registration_id = ? and is_see_a_doctor = 1", new String[]{registrationId}, null, null, null);
            while (queryRegistrationLog.moveToNext()) {
                String registrationLogId = queryRegistrationLog.getString(0);
                map.put("registrationLogId", registrationLogId);
                String userId = queryRegistrationLog.getString(1);
                String subscribeTime = queryRegistrationLog.getString(3);
                //            年月日
                String substring = subscribeTime.substring(0, 10);
//            时分秒
                String substring2 = subscribeTime.substring(11);
                map.put("appointmentTime", substring + "\n" + substring2);
                String isSeeADoctor = queryRegistrationLog.getString(4);
                Integer status = Integer.valueOf(isSeeADoctor);
                String statusToStr = "未就诊";
                if (status == 1) {
                    statusToStr = "已就诊";
                }
                //                        判断预约是否过期
                /*String atPresentDate = DateUtil.dateString(new Date(), "yyyy-MM-dd");
                String atPresentTime = DateUtil.dateString(new Date(), "HH:mm");
//                        1、判断日期是否等于当天且时间是否过期
//                        转化字符串为时间 预约就诊日期、时间
                Date registrationDate2 = DateUtil.stringDateTime(registrationDate, "yyyy-MM-dd");
                Date registrationTime2 = DateUtil.stringDateTime(registrationTime, "HH:mm");
//                        当前日期
                Date atPresentDate2 = DateUtil.stringDateTime(atPresentDate, "yyyy-MM-dd");
//                        当前时间
                Date atPresentTime2 = DateUtil.stringDateTime(atPresentTime, "HH:mm");
                if (registrationDate.equals(atPresentDate)) { // 当天
                    if (!registrationTime2.after(atPresentTime2)) { //预约时间是否小于于当前时间
                        statusToStr = "已过期";
                    }
                }*/
                map.put("setADoctorStatus", statusToStr);
//                通过用户Id查询患者姓名
                Cursor queryUser = readableDatabase.query("user", null, "id = ?", new String[]{userId}, null, null, null);
                while (queryUser.moveToNext()) {
                    String userName = queryUser.getString(1);
                    map.put("patientName", userName);
                    resultList.add(map);
                }
            }
        }
        //        判断是否具有患者预约记录
        if (resultList == null || resultList.size() == 0) {
//            toast = ToastUtil.toastHint(toast, DoctorCaseHistoryActivity.this, "暂时没有预约哦，请稍后查看！");
            return;
        }
        SimpleAdapter simpleAdapter = new SimpleAdapter(
                DoctorCaseHistoryActivity.this,
                resultList,
                R.layout.query_registration_log,
                new String[]{
                        "registrationLogId",
                        "patientName", "setADoctorStatus",
                        "appointmentTime", "setADoctorTime"
                },
                new int[]{
                        R.id.registrationLogId,
                        R.id.patientName, R.id.setADoctorStatus,
                        R.id.appointmentTime, R.id.setADoctorTime
                }
        );
        querySetADoctorListView.setAdapter(simpleAdapter);
    }

    /**
     * 断开数据库连接
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dbOpenHelper != null) {
            dbOpenHelper.close();
        }
    }

}